// pages/me/index.js
const db = wx.cloud.database()
const app = getApp()

Page({
  data: {
    openid: null,
    avatarUrl: '/images/icons/avatar.png',
    nickName: '微信用户',
    totalCheckins: 0,
    continuousDays: 0,
    monthCheckins: 0,
    currentMonthDays: 0,
    weekdays: ['日', '一', '二', '三', '四', '五', '六'],
    days: [],
    currentYear: new Date().getFullYear(),
    currentMonth: new Date().getMonth() + 1,
    loading: true
  },

  onLoad() {
    this.loadUserInfo()
    this.generateCalendar()
    this.loadCheckinData().catch(err => {
      console.error('加载打卡数据失败:', err)
      wx.showToast({ title: '数据加载失败', icon: 'none' })
      this.setData({ loading: false })
    })
  },

  // 加载用户信息
  loadUserInfo() {
    const userInfo = app.globalData.userInfo
    if (userInfo) {
      this.setData({
        avatarUrl: userInfo.avatarUrl || this.data.avatarUrl,
        nickName: userInfo.nickName || this.data.nickName
      })
    }
  },

  // 日历生成逻辑
  generateCalendar() {
    const { currentYear, currentMonth } = this.data
    // 获取当月天数
    const daysInMonth = new Date(currentYear, currentMonth, 0).getDate()
    // 获取当月第一天是周几（0=周日, 1=周一...6=周六）
    const firstDayOfWeek = new Date(currentYear, currentMonth - 1, 1).getDay()
    const days = []
    const today = new Date()
    const isCurrentMonth = currentYear === today.getFullYear() && currentMonth === today.getMonth() + 1
    // 1. 填充上月空白（如果需要）
    for (let i = 0; i < firstDayOfWeek; i++) {
      days.push({ date: '', checked: false, isToday: false })
    }
    
    // 2. 填充当月日期
    for (let i = 1; i <= daysInMonth; i++) {
      days.push({
        date: i,
        checked: false,
        isToday: isCurrentMonth && i === today.getDate()
      })
    }
    
    // 3. 补齐日历到完整周(4 x 7)
    const totalCells = 32
    while (days.length < totalCells) {
      days.push({ date: '', checked: false, isToday: false })
    }
    
    this.setData({
      days,
      currentMonthDays: daysInMonth
    })
  },

  // 打卡数据加载
  async loadCheckinData() {
    wx.showLoading({ title: '加载中...', mask: true })
    
    try {
      // 1. 获取用户openid和连续打卡天数
      const continuousRes = await wx.cloud.callFunction({
        name: 'getContinuousDays'
      }).catch(err => {
        console.warn('获取连续打卡失败, 使用默认值', err)
        return { result: { openid: '', days: 0 } }
      })
      
      const openid = continuousRes.result.openid || ''
      this.setData({ openid })
      
      if (!openid) {
        this.setData({ loading: false })
        wx.hideLoading()
        return
      }
      
      // 2. 并行获取所有必要数据
      const [totalRes, monthRes] = await Promise.all([
        db.collection('checkInRecords').where({ openid }).count(),
        db.collection('checkInRecords')
          .where({ 
            openid
          })
          .get()
      ])
      
      // 3. 处理当月打卡数据
      const checkedDates = new Set(monthRes.data.map(item => item.day))
      const days = this.data.days.map(day => {
        // 只处理当月有效日期
        if (day.date && day.date > 0 && checkedDates.has(day.date)) {
          return {...day, checked: true}
        }
        return day
      })
      // 4. 更新界面数据
      this.setData({
        days,
        totalCheckins: totalRes.total || 0,
        monthCheckins: monthRes.data.length || 0,
        continuousDays: continuousRes.result.days || 0,
        loading: false
      })
      
    } catch (err) {
      console.error('数据加载异常:', err)
      wx.showToast({ title: '数据加载异常', icon: 'error' })
    } finally {
      wx.hideLoading()
    }
  }
})